<template>
  <div class="main">
    <!-- 查询表单 -->
    <el-form :inline="true" :model="searchMap" class="demo-form-inline showtable" ref="searchMap">
      <el-form-item prop="typename">
        <el-input
          readonly
          @click.native="dialogTotalTypeVisible = true"
          v-model="searchMap.typename"
          placeholder="总商品类型请选择"
          style="width: 200px;"
          v-if="!isgoodsshow"
        ></el-input>
      </el-form-item>
      <el-form-item prop="kname">
        <el-input v-model="searchMap.kname" placeholder="请输入商品类型" style="width:200px"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit">查询</el-button>
        <el-button @click="handleAdd" type="success" v-if="!isgoodsshow">新增</el-button>
        <el-button @click="reset" v-if="!isgoodsshow">重置</el-button>
      </el-form-item>
    </el-form>
    <!-- 表格显示 -->
    <el-table
      :data="tableData"
      style="width: 100%"
      max-height="460px"
      border
      stripe
      highlight-current-row
      @current-change="clickCurrentChange"
    >
      <el-table-column type="index" label="序号" width="150" align="center"></el-table-column>
      <el-table-column
        prop="tid"
        label="总商品类型"
        width="250"
        v-if="$store.state.goodstype.totaltype.length!=0&&!isgoodsshow"
        align="center"
      >
        <template slot-scope="scope">
          <span>{{scope.row.tid | totalTypeFilter}}</span>
        </template>
      </el-table-column>
      <el-table-column prop="kname" label="商品类型" width="250" align="center"></el-table-column>
      <el-table-column prop="kimg" label="类型图片地址" width="510.5" align="center" v-if="!isgoodsshow"></el-table-column>
      <el-table-column label="操作" width="150" align="center" v-if="!isgoodsshow">
        <template slot-scope="scope">
          <el-button size="mini" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button size="mini" type="danger" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页显示 -->
    <div class="fenye">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[5, 10, 20, 30]"
        :page-size="pageSize"
        :layout="!isgoodsshow?'total, sizes, prev, pager, next, jumper':'prev, pager, next'"
        :total="total"
        hide-on-single-page
      ></el-pagination>
    </div>

    <!-- 对话框 -->
    <el-dialog
      :title="id?'编辑类型':'新增类型'"
      :visible.sync="dialogFormVisible"
      width="500px"
      top="10px"
      v-if="!isgoodsshow"
    >
      <el-form
        :model="pojo"
        ref="pojoFrom"
        label-width="100px"
        label-position="right"
        style="width: 400px;"
        status-icon
        :rules="rules"
      >
        <el-form-item prop="typename" label="总商品类型">
          <el-input
            readonly
            @click.native="dialogTotalTypeVisible = true"
            v-model="pojo.typename"
            placeholder="总商品类型请选择"
          ></el-input>
        </el-form-item>
        <el-form-item prop="kname" label="商品类型">
          <el-input v-model="pojo.kname" placeholder="商品类型"></el-input>
        </el-form-item>
        <el-form-item prop="kimg" label="类型图片">
          <el-input v-model="pojo.kimg" placeholder="类型图片地址"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="id?updatagoodsType('pojoFrom'):addType('pojoFrom')">确 定</el-button>
        <el-button @click="dialogFormVisible = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 总商品类型弹窗 -->
    <el-dialog
      title="选择总商品类型"
      :visible.sync="dialogTotalTypeVisible"
      width="500px"
      v-if="!isgoodsshow"
    >
      <total-type :isshow="true" @option-totaltype="optionTotaltype"></total-type>
    </el-dialog>
  </div>
</template>

<script>
import typeApi from "@/api/type";
//总商品类型名称
import store from "@/store";
import totalType from "@/views/totalType";
export default {
  props: {
    isgoodsshow: Boolean
  },
  data() {
    return {
      tableData: [],
      currentPage: 1, //当前页
      pageSize: 5, //一页5条数据
      total: 100,
      searchMap: {
        //查询条件
        typename: "",
        tid: "",
        kname: ""
      },
      oldDate: 0, //存旧时间
      newDate: 0, //当前时间(毫秒)
      pojo: {
        //新增会员数据
        tid: "",
        kname: "",
        kimg: "",
        typename: ""
      },
      dialogFormVisible: false, //编辑/新增对话框的显示
      dialogTotalTypeVisible: false, //总商品类型对话框的显示
      rules: {
        //新增会员验证
        tid: [{ required: true, message: "请输入总商品类型", trigger: "blur" }],
        kname: [
          { required: true, message: "请输入商品类型名", trigger: "blur" }
        ],
        kimg: [
          { required: true, message: "请输入商品类型图片地址", trigger: "blur" }
        ]
      },
      id: null,
      isEdit: false //如果是新增或编辑的对话框，就是true，如果为false就是搜索框
    };
  },

  components: { totalType },

  methods: {
    //获取分页数据
    async getSearchType() {
      try {
        //把要第几页、一页多少条、查询条件一并发给后端
        let p = await typeApi.searchType(this.currentPage, this.pageSize);
        if (p.data.flag) {
          this.tableData = p.data.data;
          this.total = p.data.total;
        }
      } catch (err) {
        console.log(err);
      }
    },
    //更换一页条数
    handleSizeChange(val) {
      //val  是当页面条数发生改变时 传入得新值  如  当页面初始条数是10 点击更换成20条 那val就是20
      this.pageSize = val;
      this.getSearchType();
    },
    //更换当前页码
    handleCurrentChange(val) {
      //val 当点击更换当前页时  val就是要更换得页码数
      this.currentPage = val;
      this.getSearchType();
    },
    //修改信息框
    handleEdit(row) {
      this.isEdit = true;
      this.dialogFormVisible = true;
      this.id = row.kid;
      // console.log(this.id);
      for (let key in this.pojo) {
        this.pojo[key] = row[key];
      }
      for (let key in this.$store.state.goodstype.totaltype) {
        if (this.pojo.tid == this.$store.state.goodstype.totaltype[key].type) {
          this.pojo.typename = this.$store.state.goodstype.totaltype[key].name;
        }
      }
    },
    //请求ajax 更新商品类型
    async updataType(kid, pojo) {
      try {
        let p = await typeApi.updatatype(kid, pojo);
        if (p.data.flag) {
          this.$message({
            message: "修改成功",
            type: "success"
          });
          this.dialogFormVisible = false;
          this.tableData.forEach(item => {
            if (item.kid == kid) {
              for (let key in pojo) {
                item[key] = pojo[key];
              }
            }
          });
          // this.getSearchType();
        } else {
          this.$message({
            message: "修改失败",
            type: "error"
          });
        }
      } catch (err) {
        console.log("ajax请求出错", err);
      }
    },
    //更新商品类型
    updatagoodsType(pojoFrom) {
      this.$refs[pojoFrom].validate(vaild => {
        if (vaild) {
          this.updataType(this.id, this.pojo);
        } else {
          this.$message({
            message: "亲，您还没填完噢",
            type: "error"
          });
        }
      });
    },
    //删除商品类型
    handleDelete(row) {
      this.$confirm("确定要删除该类型吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.deleteType(row.kid);
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    //删除商品类型，请求ajax
    async deleteType(kid) {
      try {
        let p = await typeApi.delgoodsType(kid);
        if (p.data.flag) {
          this.$message({
            type: "success",
            message: "删除成功!"
          });
          this.getSearchType();
        } else {
          this.$message({
            type: "erroe",
            message: "删除失败!"
          });
        }
      } catch (err) {
        console.log("ajax请求失败", err);
      }
    },
    //获取对应总商品类型的类型
    async getType(searchMap) {
      try {
        let p = await typeApi.getgoodsType(searchMap);
        if (p.data.flag) {
          if (p.data.data.length > this.pageSize) {
            let arr = [];
            for (let i = 0; i < this.pageSize; i++) {
              arr.push(p.data.data[i]);
            }
            this.tableData = arr;
          } else {
            this.tableData = p.data.data;
          }
          this.total = p.data.data.length;
          this.$message({
            message: "查询成功",
            type: "success"
          });
        } else {
          this.$message({
            message: "查询失败",
            type: "error"
          });
        }
      } catch (err) {
        console.log(err);
      }
    },
    //点击查询
    onSubmit() {
      let istrue = this.clickToFast();
      if (istrue) {
        this.getType(this.searchMap);
      } else {
      }
    },
    //对话框显示t
    handleAdd() {
      this.id = null;
      this.isEdit = true;
      this.dialogFormVisible = true;
      this.$nextTick(() => {
        //this.$nextTick() 它是一个异步事件，当渲染结束 之后，它的回调函数才被执行
        this.pojo = {
          //新增类型数据
          tid: "",
          kname: "",
          kimg: "",
          typename: ""
        };
        this.$refs["pojoFrom"].resetFields();
      });
    },
    //新增信息
    addType(pojoFrom) {
      this.$refs[pojoFrom].validate(valid => {
        if (valid) {
          //表单正则验证通过 发送ajax
          this.addgoodType(this.pojo);
        } else {
          //正则验证不通过
          this.$message({
            message: "请把必填的填写完整",
            type: "error"
          });
        }
      });
    },
    //添加一个新商品类型 发送ajax
    async addgoodType(pojo) {
      try {
        let p = await typeApi.addgoodsType(pojo);
        if (p.data.flag) {
          //新增成功
          this.$message({
            message: "添加成功",
            type: "success"
          });
          this.dialogFormVisible = false;
        } else {
          //新增失败
          this.$message({
            message: "添加失败",
            type: "error"
          });
        }
      } catch (err) {
        //ajax 报错
        console.log("发送ajax失败", err);
      }
    },
    //防止点击过快
    clickToFast() {
      this.oldDate = this.newDate;
      this.newDate = new Date().getTime();
      if (this.newDate - this.oldDate > 800) {
        return true;
      } else {
        return false;
      }
    },
    // 接收总商品类型 传来得数据
    optionTotaltype(currentRow) {
      // console.log(currentRow);
      this.dialogTotalTypeVisible = false;
      if (this.isEdit) {
        this.pojo.typename = currentRow.type;
        this.pojo.tid = currentRow.typeId;
      } else {
        this.searchMap.typename = currentRow.type;
        this.searchMap.tid = currentRow.typeId;
      }
      this.isEdit = false;
    },
    //重置
    reset() {
      this.$refs["searchMap"].resetFields();
      this.searchMap.tid = "";
    },
    clickCurrentChange(currentRow) {
      this.$emit("option-type", currentRow);
    }
  },
  created() {
    this.getSearchType();
    this.$store.dispatch("getTotalType");
  },
  filters: {
    //过滤器
    totalTypeFilter(type) {
      return store.state.goodstype.totaltype.filter(
        item => item.type == type
      )[0].name;
    }
  }
};
</script>

<style scoped lang="scss">
.main {
  height: 80%;
}
</style>